//
//  StatusCell.swift
//  WeiBoSwift
//
//  Created by rong on 15/7/1.
//  Copyright © 2015年 rong. All rights reserved.
//

import UIKit
import FFAutoLayout
import SDWebImage


// 转发微博cell
let StatusTransmitCellIdentifier = "StatusTransmitCellIdentifier"

// 原创微博cell
let StatusNormalCellIdentifier = "StatusNormalCellIdentifier"

/// 图片视图可重用标示符
private let PictureCellReuseIdentifier = "PictureCellReuseIdentifier"



//协议
protocol StatusCellDelagate : NSObjectProtocol {

    func statusCellDidSelectedPicture(cell: StatusCell, picIndex: Int)
}



class StatusCell: UITableViewCell, UICollectionViewDataSource, UICollectionViewDelegate{
    
    //协议变量
    weak var statusCellDelegate: StatusCellDelagate?
    
    
    //cell的可重用标识符
    class func cellIdentifier(status: Status) -> String {
    
        return status.retweeted_status != nil ? StatusTransmitCellIdentifier : StatusNormalCellIdentifier
    }
    
    //微博图片的宽度约束
    private var picWithCons: NSLayoutConstraint?
    
    //微博图片高度约束
    private var picHeigtCons: NSLayoutConstraint?
    
    /// 配图视图顶部约束
    private var topCons: NSLayoutConstraint?
    
    //转发微博的文字标签
    var transmitLabel: UILabel?
    
    ///  记录配图视图约束
    func recordPictureViewCons(cons: [NSLayoutConstraint]) {
        topCons = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Top)
        picWithCons = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Width)
        picHeigtCons = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Height)
    }
    
    var status: Status? {
        didSet {
            
            let transmitText = (status?.retweeted_status?.user?.name ?? "") + ": " + (status?.retweeted_status?.text ?? "")
            
             transmitLabel?.attributedText = EmoticonPackage.emoticonAttributeString(transmitText, font:transmitLabel!.font)
        
            //头像
            iconView.sd_setImageWithURL(status?.user?.profileURL)
            //认证图片
            vipIconView.image = status?.user?.verifiedImage
            //会员等级
            memberIconView.image = status?.user?.mbImage
            
            nameLabel.text = status?.user?.name
            //测试用的： timeLabel.text = "刚刚"
            //timeLabel.text ＝ NSDate.sinaDateWithString(status?.created_at ?? "").dateDescription()
            timeLabel.text = NSDate.sinaDateWithString(status?.created_at ?? "").dateDescription()
            sourceLabel.text = status?.source//"来自 微博"
           // print("====================> \(status?.source)")
           // contentLabel.text = status?.text
            contentLabel.attributedText = EmoticonPackage.emoticonAttributeString(status!.text ?? "", font:contentLabel.font)
            
            
            //计算图片视图的大小
            //print("计算图片视图的大小 ==> \(status.)\(calcPictureCacheSize(status!))")
            
            let picSize = calcPictureCacheSize(status!)
            topCons?.constant = picSize.viewSize.height == 0 ? 0 : 12
            picWithCons?.constant = picSize.viewSize.width
            picHeigtCons?.constant = picSize.viewSize.height
            pictureLayout.itemSize = picSize.itemSize
            
            pictureView.reloadData()
        }
    }
    

    
    // 计算行高
    func picCellRowHeight(status: Status) -> CGFloat {
    
        //给模型设置数值， 调用 didSet 方法
        self.status = status
        
        //更新布局
        layoutIfNeeded()
        
        //返回行高
        return CGRectGetMaxY(footorView.frame)
        
    }
    
    //准备配图视图
    private func prepareForPicture() {
        pictureView.backgroundColor = UIColor.clearColor()//UIColor.lightGrayColor()
        
        //数据源
        pictureView.dataSource = self
        
        //设置代理
        pictureView.delegate = self
        
        //!!!!!必须设置代理,不对
        //pictureView.delegate = self
        
        //注册可重用的cell
        pictureView.registerClass(StatusPictureCell.self, forCellWithReuseIdentifier: PictureCellReuseIdentifier)
        
        //设置collectionview的layout 
        pictureLayout.minimumInteritemSpacing = 10
        pictureLayout.minimumLineSpacing = 10
    }
    
    //!!!!!!!!!!!!!!!!!!!!!!  此函数中的  status.imageURLs  没有改成  status.picURLs
    //根据微博模型计算图片所占大小
    /**
    0. 没有图片，返回zero
    1. 单图会按照图片等比例显示
    2. 多图的图片大小固定
    3. 多图如果是4张，会按照 2 * 2 显示
    4. 多图其他数量，按照 3 * 3 九宫格显示
    */
    
    private func calcPictureCacheSize(status: Status) -> (viewSize: CGSize, itemSize: CGSize){
        
        let itemSize = CGSize(width: 90, height: 90)
        let margin: CGFloat = 10
        
        //获取图片数量 picURLs
        //let count = status.imageURLs?.count ?? 0
        let count = status.picURLs?.count ?? 0
        
        //没有图片，返回0 
        if count == 0 {
            return (CGSizeZero, itemSize)
        }
        
        //只有一张图的时候，返回原图的尺寸
        if count == 1 {
            
            //从 缓存拿到 并且创建  image
            let key = status.picURLs![0].absoluteString
            let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key)
            print("单张图片 \(key) \(image.size)")
            
            return (image.size, image.size)
        }
        
        
        //4张图片的情况
        if count == 4 {
            let width = itemSize.width*2 + margin
            return (CGSize(width: width, height: width), itemSize)
        }
        
        //多张图片的情况
        //多张图片时候，每行图片有3张
        let rowCount = 3
        //计算行数
        //2,3 ===> 1    5,6 ===> 2   7,8,9 ===> 3
        let rows = (count - 1)/rowCount + 1
        let w = itemSize.width * CGFloat(rowCount) + margin * CGFloat(rowCount - 1)
        let h = itemSize.height * CGFloat(rows) + margin * CGFloat(rowCount - 1)
        
        return (CGSize(width: w, height: h), itemSize)
    }
    
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        let screenWith = UIScreen.mainScreen().bounds.width
        
        //顶部视图
        let topView = UIView()
        topView.backgroundColor = UIColor(white: 0.5, alpha: 1)
        addSubview(topView)
        topView.ff_AlignInner(ff_AlignType.TopLeft, referView: self, size: CGSize(width: screenWith, height: 10))
        
        // frame打印出的 尺寸是 (0.0, 0.0, 320.0, 44.0)，这个尺寸对 iphone6 和 6＋ 不适用
        // print(frame)
        
        // 添加控件
        addSubview(iconView)
        addSubview(nameLabel)
        addSubview(memberIconView)
        addSubview(vipIconView)
        addSubview(timeLabel)
        addSubview(sourceLabel)
        addSubview(contentLabel)
        contentLabel.preferredMaxLayoutWidth = screenWith - 16
        addSubview(pictureView)
        addSubview(footorView)
        
        //没有调用，配图视图函数
        prepareForPicture()
        
        // 控件布局
        iconView.ff_AlignInner(ff_AlignType.TopLeft, referView: self, size: CGSizeMake(34, 34), offset: CGPointMake(12, 22))
       // iconView.image = UIImage(named: "avatar")
        
        nameLabel.ff_AlignHorizontal(ff_AlignType.TopRight, referView: iconView, size: nil, offset:CGPointMake(12, 0))
        memberIconView.ff_AlignHorizontal(ff_AlignType.CenterRight, referView: nameLabel, size: nil, offset: CGPointMake(12, 0))
        vipIconView.ff_AlignInner(ff_AlignType.BottomRight, referView: iconView, size: nil, offset: CGPointMake(8, 8))
        timeLabel.ff_AlignHorizontal(ff_AlignType.BottomRight, referView: iconView, size: nil, offset: CGPointMake(12, 0))
        sourceLabel.ff_AlignHorizontal(ff_AlignType.BottomRight, referView: timeLabel, size: nil, offset: CGPointMake(12, 0))
        contentLabel.ff_AlignVertical(ff_AlignType.BottomLeft, referView: iconView, size: nil, offset: CGPointMake(0, 12))
        
//        contentLabel.ff_AlignInner(ff_AlignType.BottomRight, referView: pictureView, size: nil, offset: CGPointMake(-8, -8))
        
       /* let picCons = pictureView.ff_AlignVertical(ff_AlignType.BottomLeft, referView: contentLabel, size: CGSize(width: 290, height: 90), offset: CGPoint(x: 0, y: 12))
        picWithCons = pictureView.ff_Constraint(picCons, attribute: NSLayoutAttribute.Width)
        picHeigtCons = pictureView.ff_Constraint(picCons, attribute: NSLayoutAttribute.Height)*/
        
        
        //页脚视图布局
        footorView.ff_AlignVertical(ff_AlignType.BottomLeft, referView: pictureView, size: CGSize(width: screenWith, height: 44), offset: CGPoint(x: -12, y: 12))
        
    }

    //如果使用storyboard 或者 xib开发，使用 fatalError 会直接崩掉
    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //数据元方法 !!!!!!!!一开始写的是imageURL，  导致图片区域只有大小，没有具体的一个个图片
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return status?.picURLs?.count ?? 0
    }
    
    
    //选中某张照片代理方法
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PictureCellReuseIdentifier, forIndexPath: indexPath) as! StatusPictureCell
        
       // !!!!!!!!!!!!!!!!!!!!!!!cell.imageURL = status!.imageURLs![indexPath.item]
        
        cell.imageURL = status!.picURLs![indexPath.item]
        
        return cell
    }
    
    
    // 返回微博图片 缩略图的 cell 的坐标 与屏幕坐标的转换
    func getScreenFrame(picIndex: Int) -> CGRect {
        let indexPath = NSIndexPath(forItem: picIndex, inSection: 0)
        let cell = pictureView.cellForItemAtIndexPath(indexPath) as! StatusPictureCell
        let screenFrame = pictureView.convertRect(cell.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
        
        return screenFrame
    }
    
    //返回 缩略图 到 大图的坐标的转换
    func getFullScreenFrame(picIndex: Int) -> CGRect {
    
        //取得已经缓存的图片
        let urlString = status!.picURLs![picIndex].absoluteString
        let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(urlString)
        
        //计算比例
        let scale = image.size.height / image.size.width
        let screenSize = UIScreen.mainScreen().bounds.size
        
        let w = screenSize.width
        let h = w * scale
        var y: CGFloat = 0
        
        if h < screenSize.height {
            y = (screenSize.height - h) * 0.5
        }
        
        return CGRect(x: 0, y: y, width: w, height: h)
    }
    

    
    //
    //点击collectionView的一个cell，响应函数(实现这个函数需要设置 delegate)
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
       // print("点击collectionView的一个cell =====> ")
       // print(status!.picURLs?[indexPath.item])
        
        //打印出来的 是 thumbnail 网址 http://ww2.sinaimg.cn/thumbnail/9e5389bbjw1etrmzlgvi9j20p00g9ac0.jpg
        //中等图片是  bmiddle    大图  是 large
        
        print("点点点点 ＝＝＝＝ ")
        
        //以前的思路 是：打开图片浏览器界面后再去 加载图片
        //现在的思路 是：点击图片，先加载，边加载边画圆，加载完成后，再显示 图片浏览器界面
        
        //先取出 url
        //let url ＝ status!.largePicUrls![indexPath.item]
        let url = status!.largePicUrls![indexPath.item]
        
        //取出cell
        let cell = pictureView.cellForItemAtIndexPath(indexPath) as! StatusPictureCell
        
        print("cell的frame ＝＝＝》 \(cell.frame)")
//        let screenFrame = pictureView.convertRect(cell.frame, fromCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
        let screenFrame = getScreenFrame(indexPath.item)
        print("转换坐标  转换坐标 ＝＝＝》 \(screenFrame)")
        
        let v = UIView(frame: getFullScreenFrame(indexPath.item))
        v.backgroundColor = UIColor.redColor()
        //UIApplication.sharedApplication().keyWindow?.addSubview(v)
        
        SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: { (bytes, totalBytes) -> Void in
            
            // 设置进度
             let progress = CGFloat(bytes) / CGFloat(totalBytes)
            
                dispatch_async(dispatch_get_main_queue()) {
                    cell.picView.progress = progress
                }
            
            }) { [unowned self] (_, error, _, _, _) -> Void in
                
            print(error)
            // 缓冲结束后，再执行这个操作
            self.statusCellDelegate?.statusCellDidSelectedPicture(self, picIndex: indexPath.item)
        }
        
        
        //statusCellDelegate?.statusCellDidSelectedPicture(self, picIndex: indexPath.item)
    }
    
    
    
    //懒加载
    lazy var iconView = UIImageView()
    
    lazy var nameLabel = UILabel(color: UIColor.darkGrayColor(), fontSize: 14)
    
    lazy var memberIconView: UIImageView = UIImageView(image: UIImage(named: "common_icon_membership_level1"))
   
    lazy var vipIconView: UIImageView = UIImageView(image: UIImage(named: "avatar_vip"))
    
    lazy var timeLabel = UILabel(color: UIColor.orangeColor(), fontSize: 10)
    
    lazy var sourceLabel = UILabel(color: UIColor.darkGrayColor(), fontSize: 10)

    lazy var contentLabel = UILabel(color: UIColor.darkGrayColor(), fontSize: 15, multiLines: true)
    
    //图像视图
    lazy var pictureLayout = UICollectionViewFlowLayout()
    lazy var pictureView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.pictureLayout)
    
    //页脚视图
     lazy var footorView: StatusFooterView = StatusFooterView()
}

//图片UICollectionView的cell
private class StatusPictureCell: UICollectionViewCell {

    //图像地址
    var imageURL: NSURL? {
        
        didSet {
            
            picView.sd_setImageWithURL(imageURL)
            //picView.image = UIImage(named: "avatar")
            
            gifIconView.hidden = !(imageURL!.absoluteString.pathExtension.lowercaseString == "gif")//false
        }
    }
    
    //这个自定义的imageview可以画圆
    private lazy var picView:ProgressImageView = ProgressImageView()//UIImageView()
    
    //gif图片显示gif图标
    private lazy var gifIconView: UIImageView = {
    
        let gifVC = UIImageView(image: UIImage(named: "timeline_image_gif"))
        gifVC.hidden = false
        
        return gifVC
    }() //UIImageView(image: UIImage(named: "timeline_image_gif"))
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        // 设置微博图片的填充模式,这一步是等比例拉伸，还有要裁线
        picView.contentMode = UIViewContentMode.ScaleAspectFill
        // 裁线
        picView.clipsToBounds = true
        
        addSubview(picView)
        addSubview(gifIconView)
        
        //布局的与整个大小一样
        picView.ff_Fill(self)
        gifIconView.ff_AlignInner(ff_AlignType.BottomRight, referView: self, size: nil)
        //size: nil CGSize(width: 27, height: 20)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

//一条微博的 “页脚” 视图

class StatusFooterView: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addSubview(transmitBtn)//transmitBtn
        addSubview(commentBtn)
        addSubview(likeBtn)
        
        backgroundColor = UIColor(white: 0.95, alpha: 1)
        
        //三个按钮布局，水平平铺
        ff_HorizontalTile([transmitBtn, commentBtn, likeBtn], insets: UIEdgeInsetsZero)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //转发 按钮
    lazy var transmitBtn: UIButton = {
        
        let btn = UIButton()
        
        btn.setTitle("转发", forState: UIControlState.Normal)
        btn.setImage(UIImage(named: "timeline_icon_retweet"), forState: UIControlState.Normal)
        btn.titleLabel?.font = UIFont.systemFontOfSize(12)
        btn.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)
        
        return btn
    }()
    
    //评论 按钮
    lazy var commentBtn: UIButton = {
        
        let btn = UIButton()
        
        btn.setTitle("评论", forState: UIControlState.Normal)
        btn.setImage(UIImage(named: "timeline_icon_comment"), forState: UIControlState.Normal)
        btn.titleLabel?.font = UIFont.systemFontOfSize(12)
        btn.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)
        
        return btn
    }()
    
    //点赞 按钮
    lazy var likeBtn: UIButton = {
        
        let btn = UIButton()
        
        btn.setTitle("点赞", forState: UIControlState.Normal)
        btn.setImage(UIImage(named: "timeline_icon_unlike"), forState: UIControlState.Normal)
        btn.titleLabel?.font = UIFont.systemFontOfSize(12)
        btn.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)
        
        return btn
    }()
}
